<template>
  <div class="video-page">
    <div>
      <Breadcrumb
          style="margin-right: 20px;"
          :router-list="historyRoute"
          @deleteOtherRoute="deleteOtherRouteMethods"
          ref="BreadcrumbRef"
      ></Breadcrumb>
      <FileContentSearchHeader
          addButtonText="添加"
          @addNewFold="addNewFold"
          @goToGroupManager="goToGroupManager"
          @startUploadFile="startUploadFile"
          @changeSearch="changeSearchMethods"
          @mutiSendFile="mutiSendFileMethods"
          @mutiDel="mutiDelHandler"
          :needList="['search', 'folder','group', 'addButton', 'delete']"
      ></FileContentSearchHeader>
    </div>

    <CommonTable
        class="commonTable"
        ref="videoTableRef"
        :is-selection="true"
        :is-show-index="true"
        :is-has-opera="true"
        :t-column-data="videoListCol"
        :remote-api="getFileList"
        :query-params="searchObj"
        :is-reserve-select="true"
        @changeRow="changeRowMethods"
    >
      <template slot="media_name" slot-scope="scope">
        <!--文件夹-->
        <div
            class="file-name-row"
            :ref="`dragBlock${scope.$index}`"
            v-if="scope.row.file_type == '1'"
            :data-id="scope.row.id"
            @click="goToNextFold(scope.row)"
            @drop="(ev) => {dropNewHandler(ev, scope.row)}"
            @dragenter.prevent
            @dragover.prevent
        >
          <img src="./images/folder.png" class="file-icon" alt="">
          <span :data-id="scope.row.id" :class="scope.row.file_type == '1'?'fold-class': ''">
            {{scope.row.noSuffixMediaName}}
          </span>
        </div>

        <div
            class="file-name-row"
            :ref="`dragBlock${scope.$index}`"
            :draggable="true"
            :data-id="scope.row.id"
            v-else
            @dragstart="dragstartMethods(scope.row)"
            @click="goToNextFold(scope.row)"
        >
          <img src="./images/program.png" class="file-icon" alt="">
          <span :data-id="scope.row.id">
            {{scope.row.noSuffixMediaName}}
          </span>
        </div>
      </template>
      <template slot="media_type" slot-scope="scope">
        {{scope.row.file_type == '1'? '文件夹': '节目'}}
      </template>
      <template slot="operate" slot-scope="scope" class="operate-btn">
        <!-- <el-button type="text" @click="sendProgrameFile(scope.row)">分发节目素材</el-button> -->
        <el-button type="text" @click="editFile(scope.row)">编辑</el-button>
        <el-button type="text" class="del-button" @click="showProgrameDelWarn(scope.row)">删除</el-button>
        <el-button v-if="$route.query.parentId && scope.row.file_type != 1" type="text" @click="moveToPrevParent(scope.row)">移动至根目录</el-button>
      </template>
    </CommonTable>


    <UploadDialog
      :show="isShowUploadDialog"
      :parentId="searchObj.parentId"
      @on-close="closeUpload"
      @on-confirm="confirmSubmitFile"
    ></UploadDialog>

    <WarnPanelDialog
        :statusProp="statusIsDelFileProp"
        warn-content="是否删除文件"
        @confirmHandler="confirmDelMethods"
        @cancelHandler="cancelHandler"
    >
    </WarnPanelDialog>

    <WarnPanelDialog
        :statusProp="statusProp"
        :is-emit-close-methods="true"
        warn-content="是否删除节目"
        cancel-text="否"
        @closeHandler="closeProgramHandlerMethods"
        @confirmHandler="confirmDelOnlyHandler"
        @cancelHandler="closeProgramHandlerMethods"
    ></WarnPanelDialog>

    <FileGroupManager
        :show="isShowGroup"
        @on-close="isShowGroup = false"
    ></FileGroupManager>

    <EditProgramInfo
        :show="isShowEditFile"
        :mediaType="searchObj.mediaType"
        :edit-info-form="editForm"
        @on-close="isShowEditFile = false;getList()"
    ></EditProgramInfo>

    <el-dialog
        title="节目信息"
        :visible.sync="editProgram"
        width="50%"
        :before-close="handleClose">
      <el-form ref="form" :model="programForm" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="节目">
              <el-input v-model="programForm.mediaName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="programForm.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="缩略图">
              <template v-if="!programForm.image">
                <el-upload
                  style="width: 100%;"
                  class="upload-demo"
                  drag
                  :show-file-list="false"
                  :on-success="uploadSuccess"
                  :action="uploadUrl"
                  :multiple="false"
                  :accept="imageFormat"
                  @drop.native="e => beforeUploadImage(e.dataTransfer.files[0])"
                >
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </el-upload>
              </template>
              <div v-else>
                <div @click="delImageIcon" class="el-icon-circle-close close-file-icon deleteFile"></div>
                <el-image
                  style="width: 100px; height: 100px"
                  :src="programForm.image"
                  fit="cover">
                </el-image>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分组">
              <el-select
                v-model="programForm.groupId"
                placeholder="分组"
                clearable
              >
                <el-option
                  v-for="(item, index) in groupList"
                  :label="item.group_name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="add-program-file">
              <el-button @click="addNewProgramFileList" type="primary">添加条目</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <el-table
          :data="programFileList"
          border
          style="width: 100%">
        <el-table-column
            type="index"
            width="50">
        </el-table-column>
        <el-table-column
            prop="date"
            label="类型"
            width="180">
          <template slot-scope="scope">
            <el-select @change="(val) => {changeTypeMethods(val, scope.row, scope.$index)}" v-model="scope.row.mediaType" placeholder="请选择">
              <el-option
                  v-for="item in fileTypeMap"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
            prop="date"
            label="名称"
            width="180">
          <template slot-scope="scope">
            <el-select v-model="scope.row.content_media_id" @change="(val) => {changeContentMethods(val, scope.row)}" placeholder="请选择">
              <el-option
                  v-for="item in allFileList.filter(per => {return (per.media_type == scope.row.mediaType && per.file_type == 2)})"
                  :key="item.id"
                  :label="item.media_name"
                  :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
<!--        <el-table-column-->
<!--            prop="date"-->
<!--            label="翻页时间（秒）"-->
<!--            width="180">-->
<!--          <template slot-scope="scope">-->
<!--            <el-input-->
<!--                placeholder="请输入翻页时间（秒）"-->
<!--                v-model="scope.row.page_time"-->
<!--            >-->
<!--            </el-input>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column
            prop="date"
            label="播放时间（秒）"
            width="180">
          <template slot-scope="scope">
            <el-input
                placeholder="请输入播放时间（秒）"
                v-model="scope.row.play_time"
                :disabled="scope.row.mediaType==1"
            >
            </el-input>
          </template>
        </el-table-column>

        <el-table-column
            prop="date"
            label="操作"
            width="180">
          <template slot-scope="scope">
            <div @click="topProgramFile(scope.$index)" class="el-icon-top"></div>
            <div @click="bottomProgramFile(scope.$index)" class="el-icon-bottom"></div>
            <div @click="delProgramFile(scope.$index)" class="el-icon-delete"></div>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="confirmSubmitProgram">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="终端列表"
      :visible.sync="showTerDialog"
      width="50%"
      :before-close="handleClose">
      <div>
        <CommonTable
          v-if="operate === 'selectClient'"
          class="commonTable"
          ref="terTableRef"
          v-loading="isLoading"
          :is-selection="true"
          :is-show-index="true"
          :is-has-opera="false"
          :remote-api="getClientList"
          :query-params="searchObj"
          :t-column-data="terminalListCol"
          :is-reserve-select="true"
          @changeRow="changeClientRowMethods"
          operating-width="180px"
        >

        </CommonTable>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="operate === 'selectClient'" @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="confirmSendFile">确 定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from './component/breadThump.vue'
import CommonTable from "@/components/Table/commonTable";
import UploadDialog from "@/components/UploadFile/index"
import {videoListCol} from "@/views/distribute/tableCol/videoListCol";
import {suffixFileMapObj} from '@/utils/config'
import {deepClone} from '@/utils'
import WarnPanelDialog from "@/components/WarnPanelDialog";
import * as service from './service'
import * as HomeService from '@/views/dashboard/service'
import {getClientList} from '../terminal/service'
import Mixins from "@/views/distribute/mixins/mixins";
import {terminalListCol} from "@/views/terminal/tableCol/terminalListCol";
import * as distributeService from "@/views/distribute/service";

export default {
  name: "video",
  mixins: [Mixins],
  components: {
    Breadcrumb,
    CommonTable,
    UploadDialog,
    WarnPanelDialog
  },
  data() {
    return {
      // terminalListCol,
      imageFormat: ".jpg,.png,.jpeg,.JPG,.PNG,.JPEG",
      isLoading: false,
      operate: 'selectClient',
      fileListOptions: [],
      programFileList: [],
      programForm: {
        mediaName: '',
        image: '',
        mediaType: 8,
        fileType: 2,
        remark: '',
        groupId:''
      },
      fileTypeMap: [],
      editProgram: false,
      isShowEditFile: false,
      isShowGroup: false,
      foldName: '',
      showFoldDialog: false,
      getClientList,
      terListCol: [],
      getFileList: service.getFileList,
      isShowUploadDialog: false,
      editForm: {
        mediaName: '',
        groupId: ''
      },
      searchObj: {
        audit: 1,
        parentId: 0,
        mediaType: 8,
        page: 1,
        pageSize: 20
      },
      searchClientObj: {
        name: '',
        groupId: '',
        page: 1,
        pageSize: 20
      },
      videoListCol,
      total: 0,
      showTerDialog: false,
      uploadUrl: window.ajaxUploadUrl + '/common/fileApi/file',
      clickCache: {},
      groupList: [],
      mutiDelList: [],
      containerCacheList: [],
      dragEnterCache: {},
      foldIDCache: {},
      historyRoute: [],
      allFileList: [],
      selectClients: [],
      clickProgrameCache: {},
      sendRecordList: [],
      changeKey: 1
    }
  },
  mounted() {
    this.fileTypeMap = [...suffixFileMapObj()]
    this.getGroupList()
    this.getAllFileList()
    this.findAllSendRecords()
    if(this.$route.query.parentId) {
      this.searchObj.parentId = this.$route.query.parentId
      this.getList()
    } else {
      this.searchObj.parentId = 0
      this.getList()
    }
  },
  watch: {
    "$route.query.parentId"(val) {
      if(val) {
        this.searchObj.parentId = val
        this.getList()
      } else {
        this.searchObj.parentId = 0
        this.getList()
      }
    }
  },
  methods: {
    beforeUploadImage(file) {
      var suffix = "."+file.name.substring(file.name.lastIndexOf(".") + 1);
      if(!this.imageFormat.includes(suffix)){
        this.$message.error('文件格式错误')
        return false;
      }
      return true;
    },
    delImageIcon() {
      this.programForm.image = ''
    },
    getGroupList() {
      const params = {
        page: 1,
        pageSize: 200000000,
        mediaType: 8
      }
      distributeService.getFileGroupList(params).then((res) => {
        this.groupList = res.data.records
      })
    },
    findAllSendRecords() {
      // 查找是否分发过
      const searchParams = {
        "clientId": '',
        page: 1,
        pageSize: 20000000
      }
      HomeService.getSendRecord(searchParams).then((res) => {
        this.sendRecordList = res.data.records.slice()
      })
    },
    closeProgramHandlerMethods() {
      console.log('接受关闭示例')
      this.statusProp = false
      this.clickCache = {}
    },
    showProgrameDelWarn(row) {
      this.statusProp = true
      this.clickCache = Object.assign({}, row)
    },
    changeClientRowMethods(rows) {
      this.selectClients = [...rows]
    },
    getClientListMethods() {
      this.$nextTick(() => {
        this.$refs.terTableRef.queryData(this.searchClientObj, () => {
          this.$refs.terTableRef.dataList.forEach((item) => {
            if(item.group_id) {
              const findIndex = this.groupList.findIndex((result) => {
                return item.group_id == result.id
              })
              if(findIndex !== -1) {
                item.group_name = this.groupList[findIndex].group_name
              }
            }
          })
          this.$refs.terTableRef.dataList.splice(0, 0)
        })
      })
    },
    terminalListCol() {
      return terminalListCol
    },
    confirmSelectTer(clientIds, mediaIds, mediaIdFields='id') {
      const params = {
        clientIds,
        mediaIds
      }
      if(clientIds.length > 0) {
        service.quicklySend(params).then(() => {
          this.$message.success('发送成功')
        })
      }
    },
    sendProgrameFile(row) {
      this.showTerDialog = true
      this.clickProgrameCache = {
        ...row
      }
      this.getClientListMethods()
    },
    confirmSendFile() {
      let programFileList = []
      let clientIdList = []
      let selectMediaList = []
      this.clickProgrameCache.programs && this.clickProgrameCache.programs.forEach((item) => {
        selectMediaList.push(item)
      })
      this.selectClients && this.selectClients.forEach((item) => {
        clientIdList.push(item.id)
      })


      let index = 0
      selectMediaList.forEach((item) => {
        clientIdList.forEach((child) => {
          index = index + 1
          const findIndex = this.sendRecordList.findIndex((result) => {
            return result.client_id == child && result.media_name == item.media_name
          })
          if(findIndex === -1) {
            programFileList.push(item.content_media_id)
          }
        })
      })

      if(programFileList.length === 0) {
        this.$message.success('已发送过内容到该终端')
        return
      }
      this.confirmSelectTer([...clientIdList], [...programFileList])
    },
    delProgramFile(index) {
      this.programFileList.splice(index, 1)
    },
    bottomProgramFile(index){
      const obj = deepClone(this.programFileList[index])
      this.programFileList.splice(index,1)
      this.programFileList.splice(index+1, 0, obj)
    },
    topProgramFile(index){
      const obj = deepClone(this.programFileList[index])
      this.programFileList.splice(index,1)
      this.programFileList.splice(index-1, 0, obj)
    },
    getAllFileList() {
      const params = {
        mediaType: '',
        page: 1,
        pageSize: 200000000
      }

      service.getFileList(params, {}).then((res) => {
        this.allFileList = res.data.records.slice()
      })
    },
    changeTypeMethods(val, row, index) {
      console.log('val ---', val, row, index, this.programFileList)
      this.$set(this.programFileList[index], 'mediaType', val)
      this.$set(this.programFileList[index], 'content_media_id', '')
      this.$set(this.programFileList[index], 'play_time', '')
      this.programFileList.splice(0, 0)
    },
    changeContentMethods(val, row) {
      console.log('val ---', val, row)
      // this.programFileList.forEach((item,key) => {
      //   if(item.id == row.id) {
      //     item.content_media_id = val
      //   }
      // })
      this.changeKey = this.changeKey + 1
    },
    changePlayTimeMethods(val, row) {
      console.log('val ---', val, row)
      // this.programFileList.forEach((item,key) => {
      //   if(item.id == row.id) {
      //     item.play_time = val
      //   }
      // })
      this.changeKey = this.changeKey + 1
    },
    addNewProgramFileList() {
      const tmp = {
        mediaType: '',
        content_media_id: '',
        // page_time: '',
        play_time: ''
      }

      this.programFileList.push(tmp)
    },
    onDragenter(ev) {
      if(!ev.target.dataset.id) {
        if(!ev.fromElement.dataset.id) {
          const cellIndex = this.$refs.videoTableRef.dataList.findIndex((result) => {
            return result.id == ev.fromElement.dataset.id
          })
          if(cellIndex !== -1) {
            const target = this.$refs.videoTableRef.dataList[cellIndex]
            this.dragEnterCache = Object.assign({}, target)
          }
        } else {
          // 在外框就用table元素获取
          const cellIndex = ev.toElement.cellIndex
          const target = this.$refs.videoTableRef.dataList[cellIndex]
          console.log('target ====', target, ev)
          this.dragEnterCache = Object.assign({}, target)
        }
      } else if(ev.target.dataset.id) {
        const cellIndex = this.$refs.videoTableRef.dataList.findIndex((result) => {
          return result.id == ev.target.dataset.id
        })
        if(cellIndex !== -1) {
          const target = this.$refs.videoTableRef.dataList[cellIndex]
          console.log('target ====', target)
          this.dragEnterCache = Object.assign({}, target)
        }
      }
    },

    goToNextFold(row) {
      if(row.file_type == 1) {
        this.pushRouterHistory(row, 'video')
        this.$refs.BreadcrumbRef.refreshMenu()
      } else {
        window.open(row.media_link)
      }
    },

    dragenterMethods(ev) {
      console.log('移动中 ---', ev.target)
    },
    changeSearchMethods(msg) {
      this.searchObj = {
        ...this.searchObj,
        ...msg
      }
      this.getList()
    },
    mutiDelHandler() {
      if(this.mutiDelList.length === 0) {
        this.$message.error('请选择删除的分组')
        return
      }
      this.statusProp = true
    },
    inputSearch() {
      this.searchObj.page = 1
      this.getList()
    },
    changeSearch() {
      this.searchObj.page = 1
      this.getList()
    },
    onCellEnterMethods(row) {
      console.log('row ---', row)
    },
    changeRowMethods(row) {
      this.mutiDelList = [...row]
    },
    addNewFold() {
      this.getList()
    },
    async confirmSubmitProgram() {
      if(this.programForm.mediaName === '') {
        this.$message.error('请输入节目名称')
        return
      }
      if(this.programFileList.length === 0) {
        this.$message.error('请添加节目条目')
        return
      }
      const params = {
        ...this.programForm
      }
      console.log('params ---', params)

      params.programs = this.programFileList.slice()

      for(let i = 0;i < params.programs.length;i++) {
        console.log('params.programs[i] ---', params.programs[i])
        if(params.programs[i].file_type != 1) {
          if(params.programs[i].content_media_id == '') {
            this.$message.error('请选择素材')
            return
          }
          console.log('params.programs[i].file_type ---', params.programs[i].mediaType)
          if(params.programs[i].mediaType != 1 && params.programs[i].play_time == '') {
            this.$message.error('请输入播放时间')
            return
          }
        }
      }

      params.programs.forEach((item) => {
        item.media_id = item.content_media_id
        delete item.mediaType
        // delete item.content_media_id
      })

      service.saveFileContent(params).then(() => {
        this.$message.success('新增成功')
        this.editProgram = false
        const params = Object.assign({}, this.searchObj)
        this.$refs.videoTableRef.queryData(params)
        this.programForm= {
          mediaName: '',
          image: '',
          mediaType: 8,
          fileType: 2,
          remark: '',
          groupId:''
        }
        this.programFileList = []
      })
    },
    handleClose() {
      this.showTerDialog = false
      this.showFoldDialog = false
      this.foldName = ''
      this.clickCache = {}
      this.editProgram = false
      this.programFileList = []
      this.programForm = {
        mediaName: '',
        image: '',
        mediaType: 8,
        fileType: 2,
        remark: '',
        groupId:''
      }
    },
    editFile(row) {
      Object.keys(this.programForm).forEach((key) => {
        this.programForm[key] = row[key]
      })
      this.programForm.id = row.id
      this.programForm.mediaType = 8
      this.programForm.fileType = 2
      this.programForm.mediaName = row.media_name
      this.programForm.groupId = row.group_id
      this.programFileList = JSON.parse(JSON.stringify(row.programs.slice()))

      this.programFileList.forEach((item, key) => {
        const filterData =  this.allFileList.filter((result) => {
          return result.media_type == item.mediaType && result.file_type != 1
        })

        console.log('filterData ---', filterData)
        // this.fileListOptions = [...filterData]
        this.$set(this.programFileList[key], 'mediaType', item.media_type.toString())
        this.$set(this.programFileList[key], 'content_media_id', item.content_media_id)
        this.$set(this.programFileList[key], 'play_time', item.play_time)
        // item.content_media_id = item.content_media_id
        // item.play_time = item.play_time
      })

      console.log('this.programFileList ---', this.programFileList)
      this.programFileList.splice(0,0)
      this.editProgram = true
      this.editForm.id = row.id
      this.editForm.auditHistory = row.auditHistory
      // this.editForm.groupId = row.groupId || row.group_id
      // this.editForm.mediaSuffix = row.media_suffix
      // this.editForm.mediaName = row.mediaName || row.media_name
      // this.editForm.mediaName = row.noSuffixMediaName
    },
    mutiSendFileMethods() {
      if(this.mutiDelList.length === 0) {
        this.$message.error('请选择分发的文件')
        return
      }
      this.showTerDialog = true
    },
    sendFile(row) {
      this.clickCache = Object.assign({}, row)
      this.showTerDialog = true
    },
    goToGroupManager() {
      this.isShowGroup = true
    },
    getList() {
      const params = Object.assign({}, this.searchObj)
      this.$refs.videoTableRef.queryData(params)
    },
    uploadSuccess(res) {
      this.programForm.image = res.data[0].file
    },
    startUploadFile() {
      this.editProgram = true
    },
    closeUpload() {
      this.isShowUploadDialog = false
    },
    confirmSubmitFile(row) {
      this.$message.success('新增成功')
      // this.isShowUploadDialog = false
      this.getList()
    },
    transformUrlLink(url) {
      return url.substring(url.lastIndexOf(".") + 1)
    },
  }
}
</script>

<style scoped lang="scss">
.video-page{
  padding: 15px;
  background: white;
  .fold-class{
    cursor: pointer;
    color: #409EFF;
  }

  .terminal-search-title{

  }

  .commonTable{
    margin-top: 15px;
  }

  .control-fixed-pos{
    display: flex;

    .upload-button{
      margin: 0 10px;
    }
  }
}

.el-icon-delete{
  cursor: pointer;
  color: #F56C6C;
}
.add-program-file{
  text-align: right;
  padding-top: 85px;
}
.el-icon-bottom, .el-icon-top{
  color: rgb(86, 204, 165);
  cursor: pointer;
}

.el-icon-bottom, .el-icon-top, .el-icon-delete{
  margin: 0 5px;
}
::v-deep .el-dialog__body{
  padding: 20px;
}
  .deleteFile{
    position: absolute;
    z-index: 1;
    left: 90px;
    top: -5px;
    cursor: pointer;
    color: red;
  }

</style>
